package com.zrb.mobile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
 
 
import com.zrb.mobile.adapter.TopAdsPagerAdapter;
import com.zrb.mobile.adapter.model.AdsDto;
import com.zrb.mobile.adapter.model.FavoriteDto;
import com.zrb.mobile.adapter.model.ProjectsDto;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.AutoScrollViewPager;
import com.zrb.mobile.ui.ZoomOutSlideTransformer;
 
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.ZrbRestClient;

import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.zrb.applib.utils.AppSetting;

public class Ads_banner_fragment extends Fragment implements OnClickListener
{
	//public static final String TITLE = "title";
	AutoScrollViewPager	mTopViewPager;
	//CirclePageIndicator  PageIndicator;
	private TextView tv_title;
 
	List<AdsDto> mCurrentData;
	TopAdsPagerAdapter mTopViewPagerAdapter;
	TextView pppTypetxt,projectAreatxt;
	TextView projectAuthType;
	ProjectsDto curProjectDto;
	
    private int DELYED= 5000;
	private LayoutInflater mInflater;
	/** �����ĸ��ѡ���  */
	private PopupWindow popupWindow;
	ImageView imgshare;
	
	private int currentItem = 0; // ��ǰͼƬ�������
	// �л���ǰ��ʾ��ͼƬ
	/*private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			mTopViewPager.setCurrentItem(currentItem);// �л���ǰ��ʾ��ͼƬ
			handler.postDelayed(ScrollTask, DELYED);
		};
	};*/
 
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		mInflater = LayoutInflater.from(this.getActivity());
		//initPopWindow();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.app_ads_banner, container, false);
 
		pppTypetxt=(TextView)view.findViewById(R.id.tv_ppptype);
		pppTypetxt.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//�Ӵ�
		pppTypetxt.getPaint().setFakeBoldText(true);//�Ӵ�
		
		projectAreatxt=(TextView)view.findViewById(R.id.tv_project_area);
		projectAuthType=(TextView)view.findViewById(R.id.tv_ad_auth);
		
		
		mTopViewPager = (AutoScrollViewPager) view.findViewById(R.id.viewpager1);
		mTopViewPager.setOffscreenPageLimit(3);
		mTopViewPager.setPageTransformer(true, new ZoomOutSlideTransformer());  
		//PageIndicator= (CirclePageIndicator) view.findViewById(R.id.id_indicator);
		//PageIndicator.setOnPageChangeListener(curPageChangeListener);
		imgshare=(ImageView)view.findViewById(R.id.img_share);
		imgshare.setOnClickListener(new popAction(1));
		imgshare.setEnabled(false);
		tv_title = (TextView) view.findViewById(R.id.tv_title);
 		return view;
 	}
 	
	public void refleshData(List<ProjectsDto> banners){
		
		if(banners!=null&&banners.size()>0){
			 showui(banners.get(0));
			 imgshare.setEnabled(true);
			 String[] tmpArr=banners.get(0).bigPic.split("#");
 		     List<AdsDto> tmplist=new ArrayList<AdsDto>();
			 for(int i=0;i<tmpArr.length;i++){
				// AdsDto tmpdto=new AdsDto();
			/*	 tmpdto.infoid=banners.get(0).autoId+"";
				 tmpdto.title=banners.get(0).projectName;
				 tmpdto.pic=tmpArr[i];*/
				// tmplist.add(tmpdto);
 			 }
 			 Log.e("tmplist:", tmplist.size()+"");
			 
		     mTopViewPagerAdapter = new TopAdsPagerAdapter(Ads_banner_fragment.this.getActivity());
		     mTopViewPagerAdapter.setInfiniteLoop(false);
		     mTopViewPagerAdapter.SetDataList(tmplist);
 	 		 mTopViewPager.setAdapter(mTopViewPagerAdapter); 
 	 		 
 	 		mTopViewPager.setInterval(5000);
 	 		mTopViewPager.stopAutoScroll();
 	 		mTopViewPager.startAutoScroll();
 	 		mTopViewPager.setCurrentItem(0);
 	 		//mTopViewPager.setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % CommonUtil.getSize(tmplist));
	    	// PageIndicator.setViewPager(mTopViewPager, 0);
 	 		//handler.removeCallbacks(ScrollTask);
 	 		//handler.postDelayed(ScrollTask, DELYED);
  		}
  	}
	
	private String getProjectType(int code){
	 	  switch (code) {
			  case Constants.pppType:
				return "PPP";
			  case Constants.purposeType:
				return "����";
			  case Constants.assetType:
				return "�ʲ�";
			  default:
				return "";
			}
	}
	
	private String replace(String tmpStr,String replaceStr){
		
		if(TextUtils.isEmpty(tmpStr)) return "";
		else
			return tmpStr.replace(replaceStr, "");
	}
	
	private void setAuthTag(TextView tagview,int code){
		
	 
	}
	
	private void showui(ProjectsDto curDto){
		
		curProjectDto=curDto;
 		pppTypetxt.setText(getProjectType(curDto.projectType));
 		projectAreatxt.setText(CommonUtil.cutString(replace(curDto.province,"ʡ"),2)+"."+CommonUtil.cutString(replace(curDto.city,"��"),2));
 		
 		setAuthTag(projectAuthType,curDto.isValidate); 
 		
		TextView mtitle=(TextView)this.getView().findViewById(R.id.tv_ad_title);
		mtitle.setText(curDto.projectName);
		
		TextView msummary=(TextView)this.getView().findViewById(R.id.tv_ad_summary);
		msummary.setText(curDto.intro);
		
		TextView mprice=(TextView)this.getView().findViewById(R.id.tv_ad_price);//��Ӫ�� |��ֵ:7540��
		
		TextView mpublishDate=(TextView)this.getView().findViewById(R.id.tv_ad_publishdate);
		mpublishDate.setText("����ʱ�䣺"+CommonUtil.formatlongDate(curProjectDto.pushTime,new SimpleDateFormat("yyyy-MM-dd")));
		
		String tmptypeZH="";
		if(curDto.projectType==Constants.purposeType)  tmptypeZH=curDto.purposeZH;    //����
		if(curDto.projectType==Constants.pppType)      tmptypeZH=curDto.pppTypeZH;    // holder.pppType.setText(curDto.pppTypeZH+" �� ");//
		if(curDto.projectType==Constants.assetType)    tmptypeZH=curDto.assetTypeZH;  // holder.pppType.setText(curDto.assetTypeZH+" �� ");
	 	
		mprice.setText(tmptypeZH+"  |  " +"��ֵ:"+curDto.investmentStr+"��");
 	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
 		 super.onActivityCreated(savedInstanceState);
 		 //LoadAds();
 	
	}
	
	@Override
	public void onResume() {
 		super.onResume();
 		if(curProjectDto!=null)  mTopViewPager.startAutoScroll();
 			//handler.postDelayed(ScrollTask, DELYED);
  	}
 
	@Override
	public void onPause()
	{
 		super.onPause() ;
 		if(curProjectDto!=null)  mTopViewPager.stopAutoScroll();
 		//handler.removeCallbacks(ScrollTask);
 		//if(isFirst) { isFirst=false;  }
 		//if(scheduledExecutorService==null&&mCurrentData!=null)  onTimeStart();
	}
	 
 

	@Override
	public void onStop() {
		// ��Activity���ɼ��ʱ��ֹͣ�л�
 		super.onStop();
	}

	/**
	 * �����л�����
	 * 
	 * @author Administrator
	 * 
	 */
	/* Runnable ScrollTask = new Runnable() {

		public void run() {
			synchronized (mTopViewPager) {
				//System.out.println("currentItem: " + currentItem);
 				
				currentItem = (currentItem + 1) %mTopViewPagerAdapter.getCount();// imageViews.size();
				handler.obtainMessage().sendToTarget(); // ͨ��Handler�л�ͼƬ
			}
		}
 	};*/
 	
    public void LoadData()
    {
    	//LoadAds();
     }

     
    private ViewPager.OnPageChangeListener curPageChangeListener=new ViewPager.OnPageChangeListener()
    {

    	/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			//currentItem = position;
			/*if(mCurrentData!=null)
			tv_title.setText(mCurrentData.get(position).title);*/
			//dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
			//dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			//oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
    	
    }; 
    
   
    
    /** 
	 * ÿ��ITEM��more��ť��Ӧ�ĵ������
	 * */
	public class popAction implements OnClickListener{
		int position;
		public popAction(int position){
			this.position = position;
		}
  	
		@Override
		public void onClick(View v) {
			int[] arrayOfInt = new int[2];
			//��ȡ�����ť�����
			v.getLocationOnScreen(arrayOfInt);
	        int x = arrayOfInt[0];
	        int y = arrayOfInt[1];
            showPop(v, x , y, position);
		}
	}
    
    /**
	 * ��ʼ��������pop
	 * */
	private void initPopWindow() {
		View popView = mInflater.inflate(R.layout.project_bar_sharepop, null);
 		
		popView.findViewById(R.id.img_share_btn).setOnClickListener(this);
		popView.findViewById(R.id.img_attention_btn).setOnClickListener(this);
		popView.findViewById(R.id.img_comment_btn).setOnClickListener(this);
		
		popupWindow = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popupWindow.setBackgroundDrawable(new ColorDrawable(0));
		//����popwindow���ֺ���ʧ����
		popupWindow.setAnimationStyle(R.style.PopMenuAnimation2);
		//btn_pop_close = (RelativeLayout) popView.findViewById(R.id.root_view);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		   case R.id.img_share_btn:
 		        shareLink();
			 break;
		   case R.id.img_attention_btn:
				break;
		   case R.id.img_comment_btn:
			   Intent intent = new Intent(this.getActivity(),Project_commentActivity.class);
			   intent.putExtra("projectId", (int)curProjectDto.autoId);
 			   startActivity(intent);
 			   break;
		}
	}
	
	private void shareLink(){
		  if(popupWindow!=null) popupWindow.dismiss();
		  if(curProjectDto!=null){
		    String url =   AppSetting.BASE_URL + "pro/proDetails?id=" + curProjectDto.autoId;
		    Intent intent = new Intent(this.getActivity(),News_ShareActivity.class);
		    intent.putExtra("title", curProjectDto.projectName);
 		    intent.putExtra("url", url);
		    startActivity(intent);
		  }
	}
	
	public void onClickCollect(int newsId) {
		// TODO Auto-generated method stub
 		if(AppSetting.curUser==null){
 			 Intent it = new Intent(this.getActivity(), User_phone_login.class);
 			 it.putExtra("forResult", true);
			 this.startActivityForResult(it, 100);
		    return;
		}
   		//http://192.168.1.21:8090/user/interest/news/doAdd? 
   		String url = String.format("user/interest/news/%1$s?id=%2$d&zrb_front_ut=%3$s&type=%4$s",
				                    "doAdd", newsId,  AppSetting.curUser.zrb_front_ut,1);
   		
    
		ZrbRestClient.get(url, null,  new AsyncHttpResponseHandler()
	  	{
 			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
 				  //showToast("������ݳ��?", Project_info_lience.this);
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
 				//loadingview.Hide();
 				String results=new String(arg2);
 				
 				//showToast(results,  News_WebContentActivity.this);
				try{
 			        Gson gson =new Gson();  
 			        FavoriteDto tmpDto=	gson.fromJson(results, FavoriteDto.class);
 			        if(tmpDto.res==1){
  			        	// showToast(!isFavorite ?"�ѹ�ע":"ȡ���ע", Project_info_lience.this);
  			        	 
  			        }										   
 			        else{}
 			        	//showToast(tmpDto.msg, Project_info_lience.this);
    			}
				catch(Exception e){
  					System.out.println("eeee!!!!"+e.getMessage());
 				}
 			}});
 	}
	/** 
	 * ��ʾpopWindow
	 * */
	public void showPop(View parent, int x, int y,final int newsId) {
		//����popwindow��ʾλ��
		  
		 x-=CommonUtil.dip2px(parent.getContext(), 120);
		//x-=parent.getWidth();
		//Log.e("showPop", x+"");
		y+=CommonUtil.dip2px(parent.getContext(), 8);
 	   // popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, x, y);
		//Log.e("showPopy", y+"");
		
		popupWindow.showAtLocation(parent,  Gravity.NO_GRAVITY, x, y);
		//��ȡpopwindow����
		popupWindow.setFocusable(true);
		//����popwindow������������򣬱�رա�
		popupWindow.setOutsideTouchable(true);
		popupWindow.update();
		if (popupWindow.isShowing()) {
			
		}
	/*	btn_pop_close.setOnClickListener(new OnClickListener() {
			public void onClick(View paramView) {
				popupWindow.dismiss();
				if(mCollectionListener!=null)
					   mCollectionListener.onClickCollect(newsId,false);
			}
		});*/
	}

	
    




}
